package cn.bocweb.spinning.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bocweb.spinning.R;
import cn.bocweb.spinning.model.Bean.ShopListBean;
import cn.bocweb.spinning.model.Bean.UserBean;
import cn.bocweb.spinning.presenter.Imp.UserPresenterImp;
import cn.bocweb.spinning.presenter.UserPresenter;
import cn.bocweb.spinning.util.Constant;
import cn.bocweb.spinning.util.DeviceUtil;
import cn.bocweb.spinning.view.adapter.IntegralChargeAdapter;
import cn.bocweb.spinning.view.common.BaseActivity;
import cn.bocweb.spinning.view.dialog.LoadingDialog;
import de.greenrobot.event.EventBus;

public class IntegralChargeActivity extends BaseActivity {

    int page = 1;
    int myScore;
    IntegralChargeAdapter adapter;
    UserPresenter mUserPresenter;
    String userid;
    List<ShopListBean.DataBean> mDataBeanList;
    LoadingDialog mLoadingDialog;

    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.recycleview)
    RecyclerView recycleview;
    @Bind(R.id.ll_rechare_note)
    LinearLayout mLlRechareNote;
    @Bind(R.id.refresh)
    SwipeRefreshLayout mRefresh;
    @Bind(R.id.imageView_banner)
    ImageView imageView_banner;
    @Bind(R.id.textview_score)
    TextView textview_score;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_integral_charge);
        EventBus.getDefault().register(this);
        ButterKnife.bind(this);

        initList();
        initToolbar();

        mLoadingDialog = new LoadingDialog(this);
        mLoadingDialog.show();

        UserBean.DataEntity dataEntity = new UserBean.DataEntity();
        dataEntity.readInfoFromLocal(this);
        userid = dataEntity.getUserid();

        mUserPresenter = new UserPresenterImp();
        mUserPresenter.getShopList(page, userid);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        if (mLoadingDialog == null) {
            mLoadingDialog = new LoadingDialog(this);
            mLoadingDialog.show();
        } else {
            mLoadingDialog.show();
        }
        mDataBeanList.clear();
        mUserPresenter.getShopList(page, userid);
    }

    @Override
    protected void onRestart() {
        super.onRestart();

    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    public void onEventMainThread(ShopListBean bean) {
        if (mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
        if (mRefresh.isRefreshing()) {
            mRefresh.setRefreshing(false);
        }
        if (bean.getReturn_code() == 0) {
            if (bean.getData().isEmpty()) {
                DeviceUtil.MyToast(this, "已经是最后一页");
            } else {
                mDataBeanList.addAll(bean.getData());
                adapter.notifyDataSetChanged();

                showBanner(bean.getBanner());

                textview_score.setText(bean.getScore());
                myScore = Integer.parseInt(bean.getScore());
            }
        } else {
            DeviceUtil.MyToast(this, bean.getMsg());
        }
    }

    private void showBanner(String banner) {
        Glide
                .with(this)
                .load(banner)
                .fitCenter()
                .into(imageView_banner);
    }

    private void initToolbar() {
        toolbar.setTitle("积分商城");
        toolbar.setTitleTextColor(getResources().getColor(R.color.white));
        toolbar.setNavigationIcon(R.mipmap.btn_exit);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initList() {
        mDataBeanList = new ArrayList<>();
        adapter = new IntegralChargeAdapter(mDataBeanList);
        GridLayoutManager manager = new GridLayoutManager(this, 2);

        recycleview.setHasFixedSize(true);
        recycleview.setLayoutManager(manager);
        recycleview.setAdapter(adapter);
        adapter.setOnItemClickListener(new IntegralChargeAdapter.OnItemClickListener() {
            @Override
            public void onClick(int postion, String url, String id) {
                Intent intent = new Intent(IntegralChargeActivity.this, IntegralProductActivity.class);
                intent.putExtra(Constant.TO_SHOP_DETAIL_URL, url);
                intent.putExtra(Constant.TO_SHOP_DETAIL_STATUS, 0);
                intent.putExtra(Constant.TO_SHOP_DETAIL_ID, id);
                intent.putExtra(Constant.TO_SHOP_DETAIL_MY_INTEGRAL, myScore);
                intent.putExtra(Constant.TO_SHOP_DETAIL_INTEGRAL, Integer.parseInt(mDataBeanList.get(postion).getScore()));
                startActivity(intent);
            }
        });

        mRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mDataBeanList.clear();
                adapter.notifyDataSetChanged();
                page = 1;
                mUserPresenter.getShopList(page, userid);
            }
        });

        recycleview.addOnScrollListener(new RecyclerView.OnScrollListener() {
            //用来标记是否正在向最后一个滑动，既是否向右滑动或向下滑动
            boolean isSlidingToLast;

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
                // 当不滚动时
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    //获取最后一个完全显示的ItemPosition
                    int lastVisibleItem = manager.findLastCompletelyVisibleItemPosition();
                    int totalItemCount = manager.getItemCount();

                    // 判断是否滚动到底部，并且是向右滚动
                    if (lastVisibleItem == (totalItemCount - 1) && isSlidingToLast) {
                        //加载更多功能的代码
                        page++;
                        mUserPresenter.getShopList(page, userid);
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //dx用来判断横向滑动方向，dy用来判断纵向滑动方向
                if (dy > 0) {
                    //大于0表示，正在向右滚动
                    isSlidingToLast = true;
                } else {
                    //小于等于0 表示停止或向左滚动
                    isSlidingToLast = false;
                }
            }
        });
    }

    @OnClick(R.id.ll_rechare_note)
    public void onClick() {
        Intent intent = new Intent(this, MyIntegralRechargeActivity.class);
        startActivity(intent);
    }
}
